/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdlib.h>
#include <string.h>
#include "Bundle.h"
#include "ArrayList.h"
#include <OSMemory.h>

#define BUNDLE_OBJ_TO_BUNDLE(x) (Bundle)x
#define BUNDLE_TO_BUNDLE_OBJ(x) (BundleType*)x


#define BUNDLE_PARAMTER_CHECK(x) \
    do{ \
        if (!x) { \
            return; \
        } \
    } while(0)

#define MAX_ITEMS	50

typedef struct _BundleType{
	ArrayList* mList;
} BundleType;


Bundle newBundle() {
    BundleType* bundle = (BundleType*)OS_MALLOC(sizeof(BundleType));
    if (!bundle) {
		return NULL;
	}

	bundle->mList = newArrayList();
    if (!bundle->mList) {
		OS_FREE(bundle);
		return NULL;
	}

	return BUNDLE_OBJ_TO_BUNDLE(bundle);
}

void deleteBundle(Bundle bundle) {
    BundleType* bd = BUNDLE_TO_BUNDLE_OBJ(bundle);
    BUNDLE_PARAMTER_CHECK(bd);
    deleteArrayList(bd->mList);
    OS_FREE(bd);
}

void putObject(Bundle bundle, int key, void* value, int size) {
	BundleType* bd = BUNDLE_TO_BUNDLE_OBJ(bundle);
    arrayListAddKeyData(bd->mList, key, value, size);
}

void putBoolean(Bundle bundle, int key, boolean value) {
    putObject(bundle, key, &value, sizeof(value));
}

void putInt(Bundle bundle, int key, int value) {
    putObject(bundle, key, &value, sizeof(value));
}

void putString(Bundle bundle, int key, const char* value) {
    putObject(bundle, key, (void*)value, strlen(value));
}

void* getObject(Bundle bundle, int key) {
	BundleType* bd = BUNDLE_TO_BUNDLE_OBJ(bundle);
	void* value = (void*)arrayListGetKeyData(bd->mList, key);
	if (!value) {
		return NULL;
	}
	return value;
}

boolean getBoolean(Bundle bundle, int key, boolean defaultValue) {
    boolean* value = (boolean*)getObject(bundle, key);
	if (!value) {
		return defaultValue;
	}
    return *value;
}

int getInt(Bundle bundle, int key, int defaultValue) {
    int* value = (int*)getObject(bundle, key);
	if (!value) {
		return defaultValue;
	}
    return *value;
}

char* getString(Bundle bundle, int key, const char* defaultValue) {
    char* value = (char*)getObject(bundle, key);
	if (!value) {
		return (char*)defaultValue;
	}
    return value;
}

